var dbUtil = require('./dbUtil');

function insertComment(blog_id, parent, parent_name, user_name, comments, email, ctime, utime, success) {
    var insertSql = "insert into comments (`blog_id`, `parent`, `parent_name`, `user_name`, `comments`, `email`, `ctime`, `utime`) values (?, ?, ?, ?, ?, ?, ?, ?);";
    var params = [blog_id, parent, parent_name, user_name, comments, email, ctime, utime];
    var connection = dbUtil.createConnection();
    connection.connect();
    connection.query(insertSql, params, function (error, result) {
        if (error == null) {
            success(result);
        } else {
            console.log(error);
        }
    }),
    connection.end();
}

function queryCommentsByBlogId(blog_id, success) {
    var querySql = "select * from comments where blog_id = ?;";
    var params = [blog_id];
    var connection = dbUtil.createConnection();
    connection.connect();
    connection.query(querySql, params, function (error, result) {
        if (error == null) {
            success(result);
        } else {
            console.log(error);
        }
    }),
    connection.end();
}

function queryBlogCommentsCount(blog_id, success) {
    var querySql = "select count(1) as count from comments where blog_id = ?;";
    var params = [blog_id];
    var connection = dbUtil.createConnection();
    connection.connect();
    connection.query(querySql, params, function (error, result) {
        if (error == null) {
            success(result);
        } else {
            console.log(error);
        }
    }),
    connection.end();
}

function queryNewComment(size, success) {
    var querySql = "select * from comments order by id desc limit ?;";
    var params = [size];
    var connection = dbUtil.createConnection();
    connection.connect();
    connection.query(querySql, params, function (error, result) {
        if (error == null) {
            success(result);
        } else {
            console.log(error);
        }
    }),
    connection.end();
}

module.exports.insertComment = insertComment;
module.exports.queryBlogCommentsCount = queryBlogCommentsCount;
module.exports.queryCommentsByBlogId = queryCommentsByBlogId;
module.exports.queryNewComment = queryNewComment;